// index page
// ============

define([ 'zepto', 'sui', 'smExtend'], function($) {
  return {
    init: function(data) {
      this.initModal(data.maxExchangeNum, data.addressId, data.creditProductId, data.productType, data.amount);
      this.clickPlusMinusBtn(data.maxExchangeNum, data.amount);
    },
    initModal: function(maxExchangeNum, addressId, creditProductId, productType, amount) {
      var that = this;
      $(document).on("click", ".exchange-button", function() {
        
        if (maxExchangeNum <= 0 || amount <= 0) {
          return;
        }
        
        if(!addressId && productType =="product") {
          $.toast("地址为空，请选择收货地址！");
          return false;
        }
       
        var html = '<div class="number-wrap">' +
                     '<div class="number"><p style="display: block; width: 100%; text-align: center;">数量：<span class="product-number"> 1 </span></p></div>' +
                     '<div class="plus-minus"><a href="javascript:void(0);" class="plus">+</a><a href="javascript:void(0);" class="minus">-</a></div>'+
                    '</div>'
        $.modal({
          title:  '兑换一下 ？',
          text: html,
          extraClass: 'exchange-modal',
          buttons: [
            {
              text: '先等等',
            },
            {
              text: '当然啦',
              onClick: function() {
                var number = parseInt($(".product-number").html())
                $.ajax({
                  type: 'POST',
                  url: window.__CTX__.root + '/credit-trading/exchange' ,
                  data: {
                    'amount' : number,
                    'creditProductId' : creditProductId,
                    'userAddressId' : addressId
                  },
                  success: function(res) {
                	 res = JSON.parse(res);
                    if(res.code == '0') {
                      $.toast("产品兑换成功");
                      setTimeout(function() {
                        window.location.href = __CTX__.root + "/credit-trading/result?orderId=" + res.data.creditOrderId;
                      }, 1000)
                    } else {
                      $.toast(res.message);
                    }
                  },
                  error: function(res) {
                    $.toast("产品兑换失败");
                  }
                })
              }
            }
          ]
        })
      })
    },
    clickPlusMinusBtn: function(maxExchangeNum, amount) {
      $(document).on("click", ".plus-minus a", function(e) {
      
        var number = parseInt($(".product-number").html())
        if($(e.currentTarget).hasClass("plus")) {
          var max = maxExchangeNum > amount ? amount : maxExchangeNum;
          number + 1 > max ? max : number++
          $(".product-number").html(number)
        } else {
          number < 1 ? number = 1 : number ;
          $(".product-number").html(number-1)
        }
      })
      
    }
  }
})